<template>
    <div class="container">
        <div class="external" :style="`left:${x}px;`">
            <div class="box" v-for="(it, index) in boxNum " :key="index"></div>
        </div>
    </div>
</template>

<script setup>
    import { ref, onMounted, watchEffect } from 'vue'
    const { boxWidth, speed, color,isFlow } = defineProps({
        directionRotate: { type: Number, default: 90 },
        boxWidth: { type: Number, default: 253 },
        speed: { type: Number, default: 100 },
        color: { type: String, default: 'red' },
        boxHeight: { type: Number, default: 30 },
        isFlow: { type: Boolean, default: false },
    })
    let flowWidth = ref(5);
    let spaceWidth = ref(5)
    const interval = ref(50)
    let boxNum = ref(parseInt(boxWidth / (flowWidth.value + spaceWidth.value) + 2))

    let x = ref(flowWidth.value + spaceWidth.value);
    let isInterval = false
    let setintervalObj

    //打开及关闭流动
    function switchFlow(sw) {
        if (sw && !isInterval) {
            setintervalObj = setInterval(() => {
                x.value--
                if (x.value <= -(flowWidth.value + spaceWidth.value) / 2) {
                    x.value = (flowWidth.value + spaceWidth.value) / 2
                }
            }, interval.value);
            isInterval = true
        }
        else if (!sw) {
            x.value = -15
            clearInterval(setintervalObj)
            isInterval = false
        }
    }

    watchEffect(() => {
        if (color === 'red')
            switchFlow(false)
        else if (color === 'green' || ((color === 'dimgray') && isFlow)) {
            switchFlow(true)

        } else switchFlow(false)
    })
    onMounted(() => {
        if (color === 'green')
            switchFlow(true)
    })
</script>


<style scoped>
    .box {
        width: calc(v-bind(flowWidth) * 1px);
        height: calc(v-bind(boxHeight) * 1px);
        background-color: v-bind(color);
        margin-right: calc(v-bind(spaceWidth) * 1px);
    }

    .container {

        position: relative;
        border: 1px solid black;
        height: calc(v-bind(boxHeight) * 1px);
        width: calc(v-bind(boxWidth) * 1px);
        overflow: hidden;
        /* background: linear-gradient(to bottom, rgb(128, 126, 126), white, rgb(128, 126, 126)); */
        background-color: rgb(65, 63, 64);
        transform: rotate(calc(v-bind(directionRotate) * 1deg));
    }

    .external {
        display: flex;
        align-items: center;
        height: calc(v-bind(boxHeight) * 1px);
        position: absolute;
    }
</style>